package com.su.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.su.dto.DishDto;
import com.su.mapper.DishMapper;
import com.su.pojo.Dish;
import com.su.pojo.DishFlavor;
import com.su.service.DishFlavorService;
import com.su.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {
    /**
     * 添加菜品信息和口味信息
     *
     * @param dishDto
     */

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Override
    @Transactional//操作两张表，开启事务
    public void saveDishAndDishFlavor(DishDto dishDto) {
        //保存菜品基本信息
        this.save(dishDto);
        //口味信息
        List<DishFlavor> flavors = dishDto.getFlavors();
        for (DishFlavor flavor : flavors) {
            //设置菜品口味信息
            flavor.setDishId(dishDto.getId());
        }
        //保存口味信息
        dishFlavorService.saveBatch(flavors);
    }

    /**
     * 根据id查询菜品和口味信息
     *
     * @param id
     * @return
     */
    @Override
    @Transactional
    public DishDto getByIdWithFlavor(Long id) {
        //查询菜品基本信息
        Dish dish = this.getById(id);
        DishDto dishDto = new DishDto();
        //查询口味信息
        LambdaQueryWrapper<DishFlavor> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishLambdaQueryWrapper.eq(DishFlavor::getDishId, dish.getId());
        List<DishFlavor> dishFlavors = dishFlavorService.list(dishLambdaQueryWrapper);
        //设置信息
        BeanUtils.copyProperties(dish, dishDto);
        dishDto.setFlavors(dishFlavors);
        return dishDto;
    }

    /**
     * 修改菜品信息
     *
     * @param dishDto
     */
    @Transactional
    @Override
    public void updateByIdWithFlavor(DishDto dishDto) {
        //修改基本信息
        this.updateById(dishDto);
        //修改口味信息
        //1.清除信息
        LambdaQueryWrapper<DishFlavor> dishFlavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishFlavorLambdaQueryWrapper.eq(DishFlavor::getDishId, dishDto.getId());
        dishFlavorService.remove(dishFlavorLambdaQueryWrapper);
        //2.设置信息
        List<DishFlavor> flavors = dishDto.getFlavors();
        for (DishFlavor flavor : flavors) {
            flavor.setDishId(dishDto.getId());
        }
        dishFlavorService.saveBatch(flavors);
    }

    /**
     * 修改菜品状态
     *
     * @param status
     * @param ids
     */
    @Override
    public void updateStatue(int status, List<Long> ids) {
        dishMapper.updateStatue(status, ids);
    }
}
